﻿#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <assert.h>
#include "token.h"
#include "logger.h"
#include "syntax/matcher.h"
using namespace std;

//从文件读入到string里
string readFileIntoString(string filename) {
	ifstream ifile(filename);
	//将文件读入到ostringstream对象buf中
	ostringstream buf;
	char ch;
	while (buf && ifile.get(ch))
		buf.put(ch);
	//返回与流对象buf关联的字符串
	return buf.str();
}

int main() {

	initLog("output.txt");
	initLogE("outputError.txt", "error.txt");

	//    Log<<123<<endl;
	//    closeLog();
	//
	//    return 0;
		//freopen("output.txt", "w", stdout);
	string str = readFileIntoString("testfile.txt");
	auto* reader = new TokenReader(str);
	auto* matcher = new Matcher(reader);

	ProgramNode* program = matcher->createProgramNode();

	if (matcher->isError()){
	    return -1;
	}
	auto *synthesizer = new Synthesizer();
	auto *memAlloc = new MemoryAllocator(synthesizer, new Register());

	program->genCode(synthesizer, memAlloc);

	freopen("mips.txt", "w", stdout);

//	cout<<".data\n"
//          "str:    .asciiz \"";
//	for(char c : str){
//	    if( c == '\n')cout<<"\\n";
//	    else cout<<c;
//	}
//	cout<<"\"\n"
//          ".text\n"
//          "\n"
//          "la $a0, str\n"
//          "li $v0, 4\n"
//          "syscall"<<std::endl;
	cout<<synthesizer->genCode()<<endl;


//	    while (str.length() > offset && str[offset] != '\0') {
//	        Token token = reader->nextToken();
//	        if(token.symbol == ENDFILE) break;
//	        assert(token.symbol != BAD);
//	        cout << SYMBOL_NAMES[token.symbol] << ' ' << token.string << endl;
//	    }



	closeLog();
	closeLogE();


	return 0;
}

